<script setup>
import {
  getGraduateMyInfoService,
  updateGraduateAvatarService,
  updateGraduateInfoService
} from '@/api/graduate'
import { ref, computed, onMounted } from 'vue'
import { uploadImageService } from '@/api/upLoadImage'
import { tempUser } from '@/assets/staticData'
import { getProvinceListService, getCityListService, getAreaListService } from '@/api/cityArea'
import { onBeforeRouteLeave } from 'vue-router'
import { useUserStore } from '@/stores'
import { getGlobalCountriesService } from '@/api/otherApi'
import { universityName } from '@/utils/otherUtils'
const userStore = useUserStore()

const form = ref({
  nickName: '',
  employmentStatus: 1, //就业状态（1-在职, 2-失业, 3-深造）
  extendedInfo: {
    personalIntro: '',
    phone: '',
    email: ''
  },
  employmentInfo: {
    locationProvince: '',
    locationDetail: '',
    locationCountry: '',
    jobTitle: '',
    locationCity: ''
  },
  educationInfo: {
    studyingAt: '',
    studyingMajor: ''
  },
  phone: ''
})
// 添加原始数据暂存
const originalForm = ref({})

const graduateInfo = ref({
  nickName: '',
  avatarUrl: '',
  employmentStatus: 1,
  major: '',
  college: '',
  graduationYear: 2025,
  extendedInfo: {
    personalIntro: '',
    phone: '',
    email: '',
    gender: '',
    politicalStatus: '',
    birthDate: '',
    realName: ''
  },
  employmentInfo: {
    locationProvince: '',
    locationDetail: '',
    locationCountry: '',
    jobTitle: '',
    locationCity: ''
  },
  educationInfo: {
    studyingAt: '',
    undergraduateSchool: '',
    studyingMajor: ''
  },
  userName: 'unknown',
  userRole: {
    code: 2,
    desc: 'unknown'
  }
})
const avatarUrl = ref('https://pic1.zhimg.com/80/v2-8bbeacad84bfddd22b5d54e3631d96ee_720w.jpg')

const getGraduateInfo = async () => {
  const res = await getGraduateMyInfoService()
  graduateInfo.value = res.data
  console.log('获取到学生全部的信息', graduateInfo.value)
  // 头像赋值需要放在异步回调内部
  if (graduateInfo.value.avatarUrl) {
    avatarUrl.value = graduateInfo.value.avatarUrl
  }
  // 逐个属性赋值给 form
  form.value = {
    nickName: graduateInfo.value.nickName || '',
    employmentStatus: graduateInfo.value.employmentStatus || 1,
    extendedInfo: {
      personalIntro: graduateInfo.value.extendedInfo?.personalIntro || '',
      phone: graduateInfo.value.extendedInfo?.phone || '',
      email: graduateInfo.value.extendedInfo?.email || ''
    },
    employmentInfo: {
      locationProvince: graduateInfo.value.employmentInfo?.locationProvince || '',
      locationDetail: graduateInfo.value.employmentInfo?.locationDetail || '',
      locationCountry: graduateInfo.value.employmentInfo?.locationCountry || '',
      jobTitle: graduateInfo.value.employmentInfo?.jobTitle || '',
      locationCity: graduateInfo.value.employmentInfo?.locationCity || ''
    },
    educationInfo: {
      studyingAt: graduateInfo.value.educationInfo?.studyingAt || '',
      degreeStatus: graduateInfo.value.educationInfo?.degreeStatus || ''
    }
  }
  initialFirstProvince()
  originalForm.value = JSON.parse(JSON.stringify(form.value))
}
getGraduateInfo()

const fileRaw = ref('')

const handlePreview = async (file) => {
  console.log('文件', file)
  fileRaw.value = file.raw

  try {
    const formData = new FormData()
    formData.append('img', fileRaw.value)
    const { data } = await uploadImageService(formData)
    console.log('上传成功头像图片URL:', data.data.url)
    avatarUrl.value = data.data.url
    // 调用更新头像服务
    const { data: updateResult } = await updateGraduateAvatarService(data.data.url)
    console.log('更新头像服务返回数据:', updateResult)
    ElMessage.success(updateResult)
    userStore.getUser() // 更新用户信息
  } catch (error) {
    console.log('上传失败:', error)
    ElMessage.error('上传失败: ' + error.message)
  }
}

const rules = {
  //昵称
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 10, message: '昵称长度在 1 到 10 个字符', trigger: 'blur' }
  ],

  // 下拉框国家
  'employmentInfo.locationCountry': [{ required: true, message: '请选择国家', trigger: 'change' }],
  // 下拉框省份
  'employmentInfo.locationProvince': [{ required: true, message: '请选择省份', trigger: 'change' }],
  'employmentInfo.locationCity': [{ required: true, message: '请选择城市', trigger: 'change' }],
  'educationInfo.degreeStatus': [{ required: true, message: '请选择学位状态', trigger: 'change' }],
  'employmentInfo.locationDetail': [
    { required: true, message: '请输入详细地址', trigger: 'change' }
  ],
  'employmentInfo.jobTitle': [{ required: true, message: '请输入职称', trigger: 'change' }],

  // 个人简介
  extendedInfo: {
    personalIntro: [
      { required: true, message: '请输入个人简介', trigger: 'blur' },
      { max: 300, message: '个人简介不能超过300字', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]
  },

  // 教育信息
  educationInfo: {
    studyingAt: [{ required: false, message: '请选择深造院校', trigger: 'change' }],
    studyingMajor: [{ required: false, message: '请输入研究生专业', trigger: 'blur' }]
  },

  // 就业信息
  employmentInfo: {
    locationCountry: [{ required: true, message: '请选择国家', trigger: 'change' }],
    locationProvince: [{ required: true, message: '请选择省份', trigger: 'change' }],
    locationCity: [{ required: true, message: '请选择城市', trigger: 'change' }],
    locationDetail: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
    jobTitle: [{ required: true, message: '请输入职称', trigger: 'change' }]
  }
}

const userRoleDesc = computed(() => {
  const arr = ['管理员', '学生', '教师']
  return arr[graduateInfo.value.userRole.code - 1]
})
// 在data部分添加学位选项数组
const degreeOptions = [
  { label: '学士', value: '学士' },
  { label: '硕士', value: '硕士' },
  { label: '博士', value: '博士' }
]
//当前深造院校
const universityOptions = ref([])
const loading = ref(false)

const loadUniversities = async (search = '') => {
  loading.value = true
  try {
    // 模拟搜索过滤
    await new Promise((resolve) => setTimeout(resolve, 200)) // 模拟延迟
    universityOptions.value = universityName.filter((item) => item.includes(search)).slice(0, 50) // 每次只加载50条
  } finally {
    loading.value = false
  }
}
// 初始化加载
onMounted(() => {
  loadUniversities()
})

const globalCountries = ref([]) // 全球国家
// 获取全球国家列表
const getGlobalCountries = async () => {
  const {
    data: { data }
  } = await getGlobalCountriesService()
  // console.log(data)
  // 1. 提取所有中文名称到新数组
  const cnNames = data.map((item) => item.m_cn_name)
  // 2. 按拼音逆序排序（使"中国"在前）
  const sortedNames = cnNames.sort((a, b) => b.localeCompare(a, 'zh'))
  // console.log('按拼音逆序排序:', sortedNames)
  globalCountries.value = sortedNames
}
getGlobalCountries()
const provinces = ref([]) // 省份
const cities = ref([]) // 城市

const getProvinces = async () => {
  const res = await getProvinceListService()
  provinces.value = res.data.list
}
getProvinces()
const municipalities = ['北京', '上海', '天津', '重庆']
const municipalitiesSuffix = ['北京市', '上海市', '天津市', '重庆市']

const getCities = async (province) => {
  if (!province) return
  // 处理4个直辖市特殊情况
  if (municipalities.includes(province)) {
    // 直辖市直接获取区县数据
    const res = await getAreaListService({ pname: province, cname: province + '市' })
    cities.value = res.data.list
    return
  }
  // 非直辖市正常获取城市数据
  const res = await getCityListService(province)
  cities.value = res.data.list
}

const handleProvinceChange = (value) => {
  form.value.employmentInfo.locationCity = '' // 清空城市选择
  getCities(value) // 获取新省份下的城市
}

const initialFirstProvince = () => {
  console.log('初始化时获取第一个省份的城市', form.value.employmentInfo.locationProvince)
  if (form.value.employmentInfo.locationProvince) {
    let tmpProvince = form.value.employmentInfo.locationProvince
    // 如果是直辖市，去除末尾的市字
    if (municipalitiesSuffix.includes(form.value.employmentInfo.locationProvince)) {
      tmpProvince = form.value.employmentInfo.locationProvince.slice(0, -1)
    }
    getCities(tmpProvince) // 获取第一个省份的城市
  }
}

const clearEmploymentInfo = () => {
  form.value.employmentInfo = {
    locationProvince: '',
    locationDetail: '',
    locationCountry: '',
    jobTitle: '',
    locationCity: ''
  }
  ElMessage.success('工作信息已清空')
}

// 添加保存按钮逻辑
const handleSave = async () => {
  try {
    // 检查就业状态与深造院校的互斥性
    const hasEmploymentInfo = Object.values(form.value.employmentInfo).some((value) => value !== '')
    if (hasEmploymentInfo && form.value.educationInfo.studyingAt) {
      ElMessage.error('就业状态与深造院校信息不可同时填写')
      return
    }

    // 构建完整提交参数
    const submitData = {
      nickName: form.value.nickName,

      extendedInfo: {
        ...form.value.extendedInfo,
        realName: graduateInfo.value.extendedInfo.realName,
        gender: graduateInfo.value.extendedInfo.gender,
        birthDate: graduateInfo.value.extendedInfo.birthDate
      },
      employmentInfo: form.value.educationInfo.studyingAt
        ? null
        : {
            ...form.value.employmentInfo
          },
      educationInfo: {
        ...form.value.educationInfo,
        undergraduateSchool: graduateInfo.value.educationInfo.undergraduateSchool,
        studyingAt: hasEmploymentInfo ? '' : form.value.educationInfo.studyingAt // 如果有就业信息，不提交深造院校信息
      }
    }

    if (hasEmploymentInfo) {
      //'就业状态（1-在职, 2-失业, 3-深造）',
      submitData.employmentStatus = 1 //'就业状态（1-在职, 2-失业, 3-深造）',
    }
    if (form.value.educationInfo.studyingAt) {
      //'就业状态（1-在职, 2-失业, 3-深造）',
      submitData.employmentStatus = 3 //'就业状态（1-在职, 2-失业, 3-深造）',
    }
    if (form.value.jobTitle === '待业中') {
      submitData.employmentStatus = 2 //'就业状态（1-在职, 2-失业, 3-深造）',
    }
    // 处理4个直辖市特殊情况,末尾加'市'字
    if (municipalities.includes(form.value.employmentInfo.locationProvince)) {
      submitData.employmentInfo.locationProvince = form.value.employmentInfo.locationProvince + '市'
    }

    console.log('提交数据:', submitData)

    const { data } = await updateGraduateInfoService(submitData)
    console.log('更新信息:', data)
    ElMessage.success(data)
    getGraduateInfo() // 刷新页面
    userStore.getUser() // 更新用户信息
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 添加页面离开检测
onBeforeRouteLeave((to, from, next) => {
  if (hasChanges.value) {
    ElMessageBox.confirm('检测到未保存的修改，确定要离开吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => next())
      .catch(() => next(false))
  } else {
    next()
  }
})

// 添加修改检测方法
const hasChanges = computed(() => {
  return JSON.stringify(form.value) !== JSON.stringify(originalForm.value)
})

window.addEventListener('beforeunload', (e) => {
  if (hasChanges.value) {
    e.preventDefault()
    e.returnValue = '您有未保存的修改，确定要离开吗？'
  }
})
</script>

<template>
  <div class="profile-page">
    <!-- 头像上传 -->
    <div class="avatar-section">
      <!-- 左边头像 -->
      <el-upload
        class="avatar-uploader"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handlePreview"
      >
        <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
        <div class="avatar-hover">
          <img
            src=""
            alt=""
          />
        </div>
      </el-upload>
      <!-- 右边基本信息 -->
      <div class="basic_info">
        <div class="name">昵称：{{ graduateInfo.nickName }}</div>
        <!-- 这里显示角色身份 -->
        <div class="role">身份：{{ userRoleDesc }}</div>
        <div class="userName">学工号：{{ graduateInfo.userName }}</div>
      </div>
    </div>

    <!-- 信息板块 -->
    <!-- 基本信息 -->
    <el-card class="info-section">
      <template #header>
        <span class="section-title">基本信息</span>
      </template>
      <el-form :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="真实姓名" prop="realName">
              {{ graduateInfo.extendedInfo.realName }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="性别" prop="gender">
              {{ graduateInfo.extendedInfo.gender }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="出生日期" prop="birthDate">
              {{ graduateInfo.extendedInfo.birthDate }}
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="政治面貌" prop="politicalStatus">
              {{ graduateInfo.extendedInfo.politicalStatus }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="个人简介" prop="extendedInfo.personalIntro">
              <el-input
                v-model="form.extendedInfo.personalIntro"
                type="textarea"
                maxlength="300"
                show-word-limit
                autosize
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model.trim="form.nickName" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系电话" prop="extendedInfo.phone">
              <el-input v-model.number="form.extendedInfo.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="电子邮箱" prop="extendedInfo.email">
              <el-input v-model="form.extendedInfo.email" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 教育信息 -->
    <el-card class="info-section">
      <template #header>
        <span class="section-title">教育信息</span>
      </template>
      <el-form :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="毕业年份" prop="graduationYear">
              {{ graduateInfo.graduationYear }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属学院" prop="major">
              {{ graduateInfo.college }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="专业名称" prop="major">
              {{ graduateInfo.major }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="本科毕业院校" prop="graduateSchool">
              {{ graduateInfo.educationInfo.undergraduateSchool }}
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="当前深造院校" prop="educationInfo.studyingAt">
              <el-select
                clearable
                filterable
                remote
                :remote-method="loadUniversities"
                :loading="loading"
                v-model="form.educationInfo.studyingAt"
              >
                <el-option
                  v-for="campus in universityOptions"
                  :key="campus"
                  :label="campus"
                  :value="campus"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 当前研究生专业 -->
          <el-col :span="24">
            <el-form-item label="研究生专业" prop="educationInfo.studyingMajor">
              <el-input
                v-model.trim="form.educationInfo.studyingMajor"
                placeholder="请输入研究生专业"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 工作信息 -->
    <el-card class="info-section">
      <template #header>
        <span class="section-title">工作信息</span>
      </template>
      <el-form :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所在国家" prop="employmentInfo.locationCountry">
              <el-select filterable v-model="form.employmentInfo.locationCountry">
                <el-option
                  v-for="country in globalCountries"
                  :key="country"
                  :label="country"
                  :value="country"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在省份/市" prop="employmentInfo.locationProvince">
              <el-select
                v-model="form.employmentInfo.locationProvince"
                @change="handleProvinceChange"
              >
                <el-option
                  v-for="province in provinces"
                  :key="province"
                  :label="province"
                  :value="province"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在城市/区" prop="employmentInfo.locationCity">
              <el-select v-model="form.employmentInfo.locationCity">
                <el-option v-for="city in cities" :key="city" :label="city" :value="city" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="employmentInfo.locationDetail">
              <el-input
                placeholder="请输入详细地址"
                v-model.trim="form.employmentInfo.locationDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="职位名称" prop="employmentInfo.jobTitle">
              <el-input placeholder="如果没有职位，请填写“待业中”"
              v-model.trim="form.employmentInfo.jobTitle" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" plain @click="clearEmploymentInfo">清空工作信息</el-button>
      </div>
    </el-card>
    <div class="action-section">
      <el-button type="primary" @click="handleSave" :disabled="!hasChanges">保存修改</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.profile-page {
  .avatar-section {
    margin-bottom: 30px;
    display: flex;
    align-items: center;

    .avatar-uploader {
      :deep(.el-upload) {
        position: relative;
        border: 1px dashed #d9d9d9;
        border-radius: 50%;
        cursor: pointer;
        overflow: hidden;

        .avatar-hover {
          display: none;
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.5);
          -webkit-box-pack: center;
          -ms-flex-pack: center;
          justify-content: center;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
          border-radius: 50%;
          // display: flex;

          img {
            width: 32px;
            height: 32px;
          }
        }

        &:hover {
          border-color: #409eff;

          .avatar-hover {
            display: flex;
          }
        }
      }

      .avatar {
        width: 120px;
        height: 120px;
        display: block;
      }
    }

    .basic_info {
      margin-left: 20px;

      div {
        margin-bottom: 5px;
      }
    }
  }

  .info-section {
    margin-bottom: 20px;

    .section-title {
      font-size: 16px;
      color: #303133;
    }

    .el-row {
      margin: 10px 0;
    }
  }

  .action-section {
    margin-top: 20px;
    text-align: center;
    // padding: 20px;
    background: #fff;
    border-radius: 4px;
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  }
}
</style>
